﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.OleDb;
using System.Threading;
using System.Data.SqlClient;
using System.Runtime.InteropServices;
using System.IO;
using System.Diagnostics;

namespace HDS
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        Code c = new Code();

        #region 共用变量
        #region API
        [DllImport("kernel32")]
        private static extern long WritePrivateProfileString(string section, string key, string val, string filePath);

        [DllImport("kernel32")]
        private static extern int GetPrivateProfileString(string section, string key, string def, StringBuilder retVal, int size, string filePath);

        [DllImport("User32.dll", CharSet = CharSet.Auto)]
        public static extern int GetWindowThreadProcessId(IntPtr hwnd, out   int ID);
        #endregion
        string ufdata = string.Empty;//数据库名
        static StringBuilder sb1;
        static StringBuilder sb2;
        static StringBuilder sb3;
        SqlConnection con;
        private static string configFilePath = Application.StartupPath + "\\config.ini";
        int logType = 0;//日志类型
        int billType = 0;//单据类型
        string logTime = string.Empty;//记录日志时间
        string rq = string.Empty;
        string cpbm = string.Empty;
        string tempCpbm = string.Empty;
        string kmbm = string.Empty;
        string zy = string.Empty;
        double jfje = 0;
        double tempJfje = 0;
        double dfje = 0;
        double tempDfje = 0;
        string bmmc = string.Empty;
        //string bmjc = string.Empty;
        string khbm = string.Empty;
        string khjc = string.Empty;
        string czm = string.Empty;
        string gddm = string.Empty;
        string gdjc = string.Empty;
        int inid = 1;
        int ino_id = 1;
        string coutno_id = string.Empty;
        string cText1 = string.Empty;
        string cText2 = string.Empty;
        string bmid = string.Empty;
        string tempDepCode = string.Empty;
        #endregion

        private void Form1_Load(object sender, EventArgs e)
        {
            sb1 = new StringBuilder(255);
            sb2 = new StringBuilder(255);
            sb3 = new StringBuilder(255);
            GetPrivateProfileString("config", "server", "", sb1, 255, configFilePath);
            GetPrivateProfileString("config", "id", "", sb2, 255, configFilePath);
            GetPrivateProfileString("config", "pwd", "", sb3, 255, configFilePath);
            LoadZT();
            LoadYear();
            btnPOOK.Enabled = true;
        }

        #region 获取帐套和年度
        private void LoadZT()
        {
            string sql = "select cacc_id,cacc_name from ua_account";
            SqlCommand com = new SqlCommand(sql, DBHelper.con);
            DBHelper.con.Open();
            using (SqlDataReader sdr = com.ExecuteReader())
            {
                while (sdr.Read())
                {
                    string id = sdr["cacc_id"].ToString();
                    string name = sdr["cacc_name"].ToString();
                    lsZT.Items.Add(id + "_" + name);
                }
            }
            DBHelper.con.Close();
        }

        private void LoadYear()
        {
            string sql = "select distinct(iyear) from ua_account_sub where iyear <> 9999 order by iyear desc";
            SqlCommand com = new SqlCommand(sql, DBHelper.con);
            DBHelper.con.Open();
            using (SqlDataReader sdr = com.ExecuteReader())
            {
                while (sdr.Read())
                {
                    string year = sdr["iyear"].ToString();
                    lsYear.Items.Add(year);
                }
            }
            DBHelper.con.Close();
        }
        #endregion

        #region excel导入dgv
        /// <summary>
        /// 获取指定 Excel 文件中工作表的数据。默认取第一个工作表。
        /// </summary>
        /// <param name="fileName">Excel 的文件名</param>
        /// <returns></returns>
        private DataTable GetDataFromExcel(String fileName, string HDR)
        {
            string sheetName = GetExcelSheetNameByIndex(fileName, 0);
            if (!String.IsNullOrEmpty(sheetName))
            {
                string commandText = String.Format("SELECT * FROM [{0}]", sheetName);
                return ExecuteDataTable(fileName, commandText, HDR);
            }
            return null;
        }

        /// <summary>
        /// 获取 Excel 文件中指定索引的工作表名称
        /// </summary>
        /// <param name="fileName">Excel 的文件名</param>
        /// <param name="sheetIndex">要获取的索引</param>
        /// <returns></returns>
        private String GetExcelSheetNameByIndex(String fileName, int sheetIndex)
        {
            string connectionString = String.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=1\";", fileName);
            using (OleDbConnection conn = new OleDbConnection(connectionString))
            {
                try
                {
                    conn.Open();
                    DataTable schemaTable = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
                    return schemaTable.Rows.Count > sheetIndex
                        ? schemaTable.Rows[sheetIndex]["TABLE_NAME"].ToString()
                        : String.Empty;
                }
                catch (OleDbException e)
                {
                    if (e.ErrorCode == -2147467259)
                    {
                        MessageBox.Show("文件为只读状态,无法打开");
                    }
                }
                return null;
            }
        }
        /// <summary>
        /// 获取指定 Excel 文件中工作表的数据。
        /// </summary>
        /// <param name="fileName">Excel 的文件名</param>
        /// <param name="commandText">查询 SQL </param>
        private DataTable ExecuteDataTable(String fileName, String commandText, string HDR)
        {
            string connectionString = String.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties=\"Excel 8.0;HDR=" + HDR + ";IMEX=1\";", fileName);
            using (OleDbDataAdapter da = new OleDbDataAdapter(commandText, connectionString))
            {
                DataSet ds = new DataSet();
                da.Fill(ds);
                return ds.Tables[0];
            }
        }
        #endregion

        #region po按钮
        /// <summary>
        /// 浏览按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnPOUrl_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofdZT = new OpenFileDialog();
            ofdZT.Filter = "Microsoft Excel 97-2003 工作表(*.xls)|*.xls";
            if (ofdZT.ShowDialog() == DialogResult.OK)
            {
                txtPOUrl.Text = ofdZT.FileName;
            }
            else
            {
                return;
            }
            DataTable importData = GetDataFromExcel(ofdZT.FileName, "no");
            dgvZT.DataSource = importData;
            txtPOUrl.Enabled = false;
            btnPOCheck.Enabled = true;
            ufdata = string.Empty;
        }

        /// <summary>
        /// 检测按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnPOCheck_Click(object sender, EventArgs e)
        {
            try
            {
                if (lsZT.SelectedItem.ToString() == "")
                {
                }
                else
                {
                    ufdata += "ufdata_" + lsZT.SelectedItem.ToString().Substring(0, 3);
                }
            }
            catch
            {
                MessageBox.Show("没有选择帐套！");
                ufdata = string.Empty;
                return;
            }
            try
            {
                if (lsYear.SelectedItem.ToString() == "")
                {
                }
                else
                {
                    ufdata += "_" + lsYear.SelectedItem.ToString();
                }
            }
            catch
            {
                MessageBox.Show("没有选择年度！");
                ufdata = string.Empty;
                return;
            }
            if (dgvZT.Rows.Count < 1)
            {
                MessageBox.Show("没有选择数据源！");
                ufdata = string.Empty;
                return;
            }
            if (!dgvZT.Rows[5].Cells[0].Value.ToString().Equals("日期") || !dgvZT.Rows[5].Cells[1].Value.ToString().Equals("傳票編號") ||
                    !dgvZT.Rows[5].Cells[2].Value.ToString().Equals("科目代碼") || !dgvZT.Rows[5].Cells[3].Value.ToString().Equals("會計科目") ||
                    !dgvZT.Rows[5].Cells[4].Value.ToString().Equals("摘要") || !dgvZT.Rows[5].Cells[5].Value.ToString().Equals("借方金額") ||
                    !dgvZT.Rows[5].Cells[6].Value.ToString().Equals("貸方金額") || !dgvZT.Rows[5].Cells[7].Value.ToString().Equals("部門") ||
                    !dgvZT.Rows[5].Cells[8].Value.ToString().Trim().Equals("客戶/廠商 代碼") || !dgvZT.Rows[5].Cells[9].Value.ToString().Equals("客戶/廠商") ||
                    !dgvZT.Rows[5].Cells[10].Value.ToString().Equals("沖帳碼") || !dgvZT.Rows[5].Cells[11].Value.ToString().Equals("工地代碼") ||
                    !dgvZT.Rows[5].Cells[12].Value.ToString().Equals("工地簡稱"))
            {
                MessageBox.Show("文件格式检测不正确");
                return;
            }
            else
            {
                if (dgvZT.Rows[0].Cells[0].Value.ToString().Equals("汉科系统科技（上海）有限公司"))
                {
                    MessageBox.Show("模板检测为汉科");
                    billType = 1;
                }
                else if (dgvZT.Rows[0].Cells[0].Value.ToString().Equals("汉群贸易（上海）有限公司"))
                {
                    MessageBox.Show("模板检测为汉群");
                    billType = 2;
                }
                else
                {
                    MessageBox.Show("判断模板类别失败!");
                    return;
                }
                for (int i = 0; i <= 6; i++)
                {
                    DataRowView drv = dgvZT.Rows[0].DataBoundItem as DataRowView;
                    drv.Delete();
                }
                btnPOCheck.Enabled = false;
            }
            pbLoad.Maximum = dgvZT.Rows.Count;
            bgwPOCheck.RunWorkerAsync();
        }

        /// <summary>
        /// 导入按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnPOOK_Click(object sender, EventArgs e)
        {
            pbLoad.Value = 0;
            bgwPO.RunWorkerAsync();
        }
        #endregion

        #region 检测线程
        private void bgwPOCheck_DoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker worker = sender as BackgroundWorker;
            while (worker.CancellationPending == false)
            {
                for (int i = 0; i < dgvZT.Rows.Count; i++)
                {
                    worker.ReportProgress(0, i);
                    Thread.Sleep(100);
                }
                bgwPOCheck.CancelAsync();//结束
            }
        }

        private void bgwPOCheck_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            pbLoad.PerformStep();
            int i = (int)e.UserState;
            try
            {
                rq = dgvZT.Rows[i].Cells[0].Value.ToString().Trim();//获取日期
                cpbm = dgvZT.Rows[i].Cells[1].Value.ToString().Trim();//获取传票编码
                kmbm = dgvZT.Rows[i].Cells[2].Value.ToString().Trim();//获取科目编码
                zy = dgvZT.Rows[i].Cells[4].Value.ToString().Trim();//获取摘要
                jfje = Convert.ToDouble(dgvZT.Rows[i].Cells[5].Value.ToString().Trim());//获取借方金额
                dfje = Convert.ToDouble(dgvZT.Rows[i].Cells[6].Value.ToString().Trim());//获取贷方金额
                bmmc = dgvZT.Rows[i].Cells[7].Value.ToString().Trim();//获取部门
                khbm = dgvZT.Rows[i].Cells[8].Value.ToString().Trim();//获取客户
                khjc = dgvZT.Rows[i].Cells[9].Value.ToString().Trim();//获取客户简称
                czm = dgvZT.Rows[i].Cells[10].Value.ToString().Trim();//获取冲账码
                gddm = dgvZT.Rows[i].Cells[11].Value.ToString().Trim();//获取工地代码
                gdjc = dgvZT.Rows[i].Cells[12].Value.ToString().Trim();//获取工地简称
                //bmjc = dgvZT.Rows[i].Cells[13].Value.ToString().Trim();//获取部门简称
            }
            catch
            {
                MessageBox.Show("获取字段时出现错误");
                btnPOCheck.Enabled = true;
                return;
            }
            selectTwToCn_Code();
            selectCode();

            if (kmbm == "113301")
            {

            }

            if (!c.IsNull)//如果科目存在
            {
                if (c.Bend)//科目为末级
                {
                    if (c.Bitem)//项目核算
                    {
                        if (gddm == "")//工地代码(项目代码)为空
                        {
                            if (findList("科目" + kmbm + "为项目核算,工地代码不能为空"))
                            {
                                txtInfo2.Text += i + 8 + "科目" + kmbm + "为项目核算,工地代码不能为空" + "\n";
                                listBox1.Items.Add("科目" + kmbm + "为项目核算,工地代码不能为空");
                            }
                            else
                            {
                                txtInfo.Text += i + 8 + "科目" + kmbm + "为项目核算,工地代码不能为空" + "\n";
                            }
                        }
                        else
                        {
                            //查询项目代码存不存在
                            if (!selectFitemss97())
                            {
                                if (findList("科目" + kmbm + "为项目核算,工地代码不存在"))
                                {
                                    txtInfo2.Text += i + 8 + "科目" + kmbm + "为项目核算,工地代码不存在" + "\n";
                                    listBox1.Items.Add("科目" + kmbm + "为项目核算,工地代码不存在");
                                }
                                else
                                {
                                    txtInfo.Text += i + 8 + "科目" + kmbm + "为项目核算,工地代码不存在" + "\n";

                                }
                                //项目不存在,新建
                                insertFitemss97(i);
                            }
                        }
                    }
                    else
                    {
                        if (gddm != "")
                        {
                            if (findList("科目" + kmbm + "不为项目核算"))
                            {
                                txtInfo2.Text += i + 8 + "科目" + kmbm + "不为项目核算" + "\n";
                                listBox1.Items.Add("科目" + kmbm + "不为项目核算");

                            }
                            else
                            {

                                txtInfo.Text += i + 8 + "科目" + kmbm + "不为项目核算" + "\n";
                            }
                        }
                    }
                    if (c.Bcus)//客户核算
                    {
                        if (khbm == "")
                        {
                            if (findList("科目" + kmbm + "为客户核算,客户代码不能为空"))
                            {

                                txtInfo2.Text += i + 8 + "科目" + kmbm + "为客户核算,客户代码不能为空" + "\n";
                                listBox1.Items.Add("科目" + kmbm + "为客户核算,客户代码不能为空");
                            }
                            else
                            {

                                txtInfo.Text += i + 8 + "科目" + kmbm + "为客户核算,客户代码不能为空" + "\n";
                            }
                        }
                        else
                        {
                            //查询客户代码存不存在
                            if (!selectCustomer())
                            {
                                if (findList("科目" + kmbm + "为客户核算,客户代码不存在"))
                                {
                                    txtInfo2.Text += i + 8 + "科目" + kmbm + "为客户核算,客户代码不存在" + "\n";
                                    listBox1.Items.Add("科目" + kmbm + "为客户核算,客户代码不存在");

                                }
                                else
                                {

                                    txtInfo.Text += i + 8 + "科目" + kmbm + "为客户核算,客户代码不存在" + "\n";
                                }
                                //客户不存在,新建
                                insertCustomer(i);
                            }
                        }
                    }
                    else
                    {
                        if (!c.Bsup && !c.Bperson)
                        {
                            if (khbm != "")
                            {
                                if (findList("科目" + kmbm + "不为客户/供应商/个人核算"))
                                {
                                    txtInfo2.Text += i + 8 + "科目" + kmbm + "不为客户/供应商/个人核算" + "\n";
                                    listBox1.Items.Add("科目" + kmbm + "不为客户/供应商/个人核算");

                                }
                                else
                                {
                                    txtInfo.Text += i + 8 + "科目" + kmbm + "不为客户/供应商/个人核算" + "\n";

                                }
                            }
                        }
                    }
                    if (c.Bdept)//部门核算
                    {
                        if (bmmc == "")
                        {
                            if (findList("科目" + kmbm + "为部门核算,部门代码不能为空"))
                            {
                                txtInfo2.Text += i + 8 + "科目" + kmbm + "为部门核算,部门代码不能为空" + "\n";
                                listBox1.Items.Add("科目" + kmbm + "为部门核算,部门代码不能为空");

                            }
                            else
                            {

                                txtInfo.Text += i + 8 + "科目" + kmbm + "为部门核算,部门代码不能为空" + "\n";
                            }
                        }
                        else
                        {
                            selectTwToCn_Department();//转换部门,获取大陆部门id
                            //if (bmid != "0")//对照表里有部门编码
                            //{ 
                                //查询部门代码存不存在
                                if (!selectDepartment())//如果编码在用友不存在
                                {
                                    selectDepartment_cDepCode();
                                    if (findList("科目" + kmbm + "为部门核算,部门代码不存在"))
                                    {
                                        txtInfo2.Text += i + 8 + "科目" + kmbm + "为部门核算,部门代码不存在" + "\n";
                                        listBox1.Items.Add("科目" + kmbm + "为部门核算,部门代码不存在");
                                    }
                                    else
                                    {
                                        txtInfo.Text += i + 8 + "科目" + kmbm + "为部门核算,部门代码不存在" + "\n";
                                    }
                                    //部门不存在,新建
                                    insertDepartment(i);

                                }
                            //}
                        }
                    }
                    else
                    {
                        if (bmmc != "")
                        {
                            if (findList("科目" + kmbm + "不为部门核算"))
                            {
                                txtInfo2.Text += i + 8 + "科目" + kmbm + "不为部门核算" + "\n";
                                listBox1.Items.Add("科目" + kmbm + "不为部门核算");

                            }
                            else
                            {

                                txtInfo.Text += i + 8 + "科目" + kmbm + "不为部门核算" + "\n";
                            }
                        }
                    }
                    if (c.Bperson)//个人核算
                    {
                        if (khbm == "")
                        {
                            if (findList("科目" + kmbm + "为个人核算,个人代码不能为空"))
                            {
                                txtInfo2.Text += i + 8 + "科目" + kmbm + "为个人核算,个人代码不能为空" + "\n";
                                listBox1.Items.Add("科目" + kmbm + "为个人核算,个人代码不能为空");

                            }
                            else
                            {

                                txtInfo.Text += i + 8 + "科目" + kmbm + "为个人核算,个人代码不能为空" + "\n";
                            }
                        }
                        else
                        {
                            //查询客户代码存不存在
                            if (!selectPerson())
                            {
                                if (findList("科目" + kmbm + "为个人核算,个人代码不存在"))
                                {
                                    txtInfo2.Text += i + 8 + "科目" + kmbm + "为个人核算,个人代码不存在" + "\n";
                                    listBox1.Items.Add("科目" + kmbm + "为个人核算,个人代码不存在");

                                }
                                else
                                {

                                    txtInfo.Text += i + 8 + "科目" + kmbm + "为个人核算,个人代码不存在" + "\n";
                                }
                                //客户不存在,新建
                                insertPerson(i);
                            }
                        }
                    }
                    else
                    {
                        if (!c.Bcus && !c.Bsup)
                        {
                            if (khbm != "")
                            {
                                if (findList("科目" + kmbm + "不为客户/供应商/个人核算"))
                                {
                                    txtInfo2.Text += i + 8 + "科目" + kmbm + "不为客户/供应商/个人核算" + "\n";
                                    listBox1.Items.Add("科目" + kmbm + "不为客户/供应商/个人核算");
                                }
                                else
                                {

                                    txtInfo.Text += i + 8 + "科目" + kmbm + "不为客户/供应商/个人核算" + "\n";
                                }
                            }
                        }
                    }
                    if (c.Bsup)//供应商核算
                    {
                        if (khbm == "")
                        {
                            if (findList("科目" + kmbm + "为供应商核算,供应商代码不能为空"))
                            {
                                txtInfo2.Text += i + 8 + "科目" + kmbm + "为供应商核算,供应商代码不能为空" + "\n";
                                listBox1.Items.Add("科目" + kmbm + "为供应商核算,供应商代码不能为空");

                            }
                            else
                            {

                                txtInfo.Text += i + 8 + "科目" + kmbm + "为供应商核算,供应商代码不能为空" + "\n";
                            }
                        }
                        else
                        {
                            //查询供应商代码存不存在
                            if (!selectVendor())
                            {
                                if (findList("科目" + kmbm + "为供应商核算,供应商代码不存在"))
                                {
                                    txtInfo2.Text += i + 8 + "科目" + kmbm + "为供应商核算,供应商代码不存在" + "\n";
                                    listBox1.Items.Add("科目" + kmbm + "为供应商核算,供应商代码不存在");
                                }
                                else
                                {

                                    txtInfo.Text += i + 8 + "科目" + kmbm + "为供应商核算,供应商代码不存在" + "\n";
                                }
                                //供应商不存在,新建
                                insertVendor(i);
                            }
                        }
                    }
                    else
                    {
                        if (!c.Bcus && !c.Bperson)
                        {
                            if (khbm != "")
                            {
                                if (findList("科目" + kmbm + "不为客户/供应商/个人核算"))
                                {
                                    txtInfo2.Text += i + 8 + "科目" + kmbm + "不为客户/供应商/个人核算" + "\n";
                                    listBox1.Items.Add("科目" + kmbm + "不为客户/供应商/个人核算");
                                }
                                else
                                {

                                    txtInfo.Text += i + 8 + "科目" + kmbm + "不为客户/供应商/个人核算" + "\n";
                                }
                            }
                        }
                    }
                }
                else
                {
                    txtInfo.Text += i + 8 + "科目" + kmbm + "不为末级" + "\n";
                }
            }
            else
            {
                txtInfo.Text += i + 8 + "科目" + kmbm + "不存在" + "\n";
            }
            if (i != 0)
            {
                if (cpbm != tempCpbm)
                {
                    if (tempDfje.ToString() != tempJfje.ToString())//判断上一行的借贷
                    {
                        txtInfo.Text += i + 7 + "借代不平衡" + "\n";
                    }
                    tempCpbm = cpbm;
                    tempDfje = 0;
                    tempJfje = 0;
                    tempDfje += dfje;
                    tempJfje += jfje;
                }
                else
                {
                    tempDfje += dfje;
                    tempJfje += jfje;
                }
            }
            else
            {
                tempCpbm = cpbm;
                tempDfje += dfje;//取第一行
                tempJfje += jfje;
            }
            if (i + 1 == dgvZT.Rows.Count)
            {
                if (tempDfje.ToString() != tempJfje.ToString())//判断最后一行的借贷
                {
                    txtInfo.Text += i + 8 + "借代不平衡" + "\n";
                }
            }
            if (rq == "" || cpbm == "" || kmbm == "" || zy == "")
            {
                txtInfo.Text += i + 8 + "主要字段出现空值" + "\n";
            }
        }
        private bool findList(string j)
        {
            for (int i = 0; i < listBox1.Items.Count; i++)
            {
                if (listBox1.Items[i].ToString() == j)
                {
                    return false;
                }
            }
            return true;
        }
        private void bgwPOCheck_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            MessageBox.Show("检测完成");
            btnPOOK.Enabled = true ;
        }
        #endregion

        #region po导入线程
        private void bgwPO_DoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker worker = sender as BackgroundWorker;
            while (worker.CancellationPending == false)
            {
                for (int i = 0; i < dgvZT.Rows.Count; i++)
                {
                    worker.ReportProgress(0, i);
                    Thread.Sleep(100);
                }
                bgwPO.CancelAsync();//结束
            }
        }

        private void bgwPO_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            pbLoad.PerformStep();
            int i = (int)e.UserState;
            try
            {
                rq = dgvZT.Rows[i].Cells[0].Value.ToString().Trim();//获取日期
                cpbm = dgvZT.Rows[i].Cells[1].Value.ToString().Trim();//获取传票编码
                kmbm = dgvZT.Rows[i].Cells[2].Value.ToString().Trim();//获取科目编码
                zy = dgvZT.Rows[i].Cells[4].Value.ToString().Trim();//获取摘要
                jfje = Convert.ToDouble(dgvZT.Rows[i].Cells[5].Value.ToString().Trim());//获取借方金额
                dfje = Convert.ToDouble(dgvZT.Rows[i].Cells[6].Value.ToString().Trim());//获取贷方金额
            }
            catch
            {
                MessageBox.Show("获取字段时出现错误");
                btnPOCheck.Enabled = true;
                return;
            }
            selectTwToCn_Code();
            selectCode();
            if (cpbm == "20120207021")
            { 
            
            }
            if (cpbm != tempCpbm || i == 0)
            {
                inid = 1;
                selectGL_accvouch();
                ino_id++;
                string temp = Convert.ToString(Convert.ToInt64(10000000000000) + Convert.ToInt32(ino_id));
                coutno_id = "GL" + temp.Substring(temp.Length - 13);
                cText1 = cpbm.Substring(0, 4);
                cText2 = cpbm.Substring(4, 7);
                tempCpbm = cpbm;
            }
            else
            {
                inid++;
            }
            if (kmbm == "113301")
            {

            }
            if (cpbm == "20120227001")
            {

            }
            if (c.Bitem)
            {
                gddm = dgvZT.Rows[i].Cells[11].Value.ToString().Trim();//获取工地代码 项目核算
                if (c.Bcus && c.Bdept)
                {
                    khbm = dgvZT.Rows[i].Cells[8].Value.ToString().Trim();//获取客户
                    bmmc = dgvZT.Rows[i].Cells[7].Value.ToString().Trim();//获取部门
                    selectTwToCn_Department();
                    insertGL_accvouch(5, i);
                }
                else if (c.Bsup && c.Bdept)
                {
                    khbm = dgvZT.Rows[i].Cells[8].Value.ToString().Trim();//获取客户
                    bmmc = dgvZT.Rows[i].Cells[7].Value.ToString().Trim();//获取部门
                    selectTwToCn_Department();
                    insertGL_accvouch(6, i);
                }
                else if (c.Bperson)
                {
                    khbm = dgvZT.Rows[i].Cells[8].Value.ToString().Trim();//获取客户
                    insertGL_accvouch(7, i);
                }
                else if (c.Bsup)
                {
                    khbm = dgvZT.Rows[i].Cells[8].Value.ToString().Trim();//获取客户
                    insertGL_accvouch(8, i);
                }
                else if (c.Bcus)
                {
                    khbm = dgvZT.Rows[i].Cells[8].Value.ToString().Trim();//获取客户
                    insertGL_accvouch(9, i);
                }
                else if (c.Bdept)
                {
                    bmmc = dgvZT.Rows[i].Cells[7].Value.ToString().Trim();//获取部门
                    selectTwToCn_Department();
                    insertGL_accvouch(10, i);
                }
                else
                {
                    insertGL_accvouch(1, i);
                }
            }
            else
            {
                if (c.Bsup)//供应商
                {
                    khbm = dgvZT.Rows[i].Cells[8].Value.ToString().Trim();//获取客户
                    insertGL_accvouch(2, i);
                }
                else if (c.Bdept)//部门
                {
                    bmmc = dgvZT.Rows[i].Cells[7].Value.ToString().Trim();//获取部门
                    selectTwToCn_Department();
                    insertGL_accvouch(3, i);
                }
                else if (c.Bcus)//客户
                {
                    khbm = dgvZT.Rows[i].Cells[8].Value.ToString().Trim();//获取客户
                    insertGL_accvouch(4, i);
                }
                else if (c.Bperson)
                {
                    khbm = dgvZT.Rows[i].Cells[8].Value.ToString().Trim();//获取客户
                    selectPerson_cDepCode();
                    insertGL_accvouch(12, i);
                }
                else
                {
                    insertGL_accvouch(11, i);
                }
            }
        }

        private void bgwPO_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            updateAp_CancelNo();
            MessageBox.Show("导入完成");
            Process.Start(@"D:\U851SOFT\ZW\PzInsert.exe");
        }
        #endregion

        #region 检测新建编码，客户，供应商，部门，项目
        private void selectCode()
        {
            con = new SqlConnection("Data Source=" + sb1 + ";Initial Catalog=" + ufdata + ";User ID=" + sb2 + ";Password=" + sb3 + "");
            string sql = string.Format("select ccode,bdept,bcus,bperson,bsup,bitem,bend from code where ccode='{0}'", kmbm);
            SqlCommand com = new SqlCommand(sql, con);
            con.Open();
            try
            {
                using (SqlDataReader sdr = com.ExecuteReader())
                {
                    if (sdr.Read())
                    {
                        c.Ccode = sdr["Ccode"].ToString();
                        c.Bsup = Convert.ToBoolean(sdr["Bsup"]);
                        c.Bperson = Convert.ToBoolean(sdr["Bperson"]);
                        c.Bitem = Convert.ToBoolean(sdr["Bitem"]);
                        c.Bend = Convert.ToBoolean(sdr["Bend"]);
                        c.Bdept = Convert.ToBoolean(sdr["Bdept"]);
                        c.Bcus = Convert.ToBoolean(sdr["Bcus"]);
                        c.IsNull = false;
                    }
                    else
                    {
                        c.IsNull = true;
                    }
                }
            }
            catch (SqlException e)
            {
                MessageBox.Show(e.ToString());
            }
            con.Close();
        }

        private void selectTwToCn_Department()
        {
            con = new SqlConnection("Data Source=" + sb1 + ";Initial Catalog=" + ufdata + ";User ID=" + sb2 + ";Password=" + sb3 + "");
            try
            {
                string sql = string.Format("select cnid from TwToCn_Department where twName='{0}'", bmmc);
                SqlCommand com = new SqlCommand(sql, DBHelper.con);
                DBHelper.con.Open();
                bmid = com.ExecuteScalar().ToString();
            }
            catch
            {

            }
            finally
            {
                DBHelper.con.Close();
            }
            if (bmid == "")
            {
                bmid = "0";
            }
        }

        //private void selectDepartment_TwToCn()
        //{
        //    con = new SqlConnection("Data Source=" + sb1 + ";Initial Catalog=" + ufdata + ";User ID=" + sb2 + ";Password=" + sb3 + "");
        //    try
        //    {
        //        string sql = string.Format("select cnid from TwToCn_Department where twName='{0}'", bmmc);
        //        SqlCommand com = new SqlCommand(sql, DBHelper.con);
        //        DBHelper.con.Open();
        //        bmid = com.ExecuteScalar().ToString();
        //    }
        //    catch
        //    {

        //    }
        //    finally
        //    {
        //        DBHelper.con.Close();
        //    }
        //    if (bmid == "")
        //    {
        //        bmid = "0";
        //    }
        //}

        private void selectTwToCn_Code()
        {
            string tempCode = string.Empty;
            con = new SqlConnection("Data Source=" + sb1 + ";Initial Catalog=" + ufdata + ";User ID=" + sb2 + ";Password=" + sb3 + "");
            try
            {
                string sql = string.Format("select cnCode from TwToCn_Code where twCode='{0}' and type='{1}'", kmbm, billType);
                SqlCommand com = new SqlCommand(sql, DBHelper.con);
                DBHelper.con.Open();
                tempCode = com.ExecuteScalar().ToString();
            }
            catch
            {

            }
            finally
            {
                DBHelper.con.Close();
            }
            if (tempCode != "")
            {
                kmbm = tempCode;
            }
        }

        private bool selectDepartment()
        {
            int isok = 0;
            con = new SqlConnection("Data Source=" + sb1 + ";Initial Catalog=" + ufdata + ";User ID=" + sb2 + ";Password=" + sb3 + "");
            try
            {
                string sql = string.Format("select count(*) from Department where cDepCode='{0}'", bmid);
                SqlCommand com = new SqlCommand(sql, con);
                con.Open();
                isok = Convert.ToInt32(com.ExecuteScalar());
            }
            catch
            {
               
            }
            finally
            {
                con.Close();
            }
            if (isok > 0)
            {
                return true;
            }
            return false;
        }

        private void selectDepartment_cDepCode()
        {
            int temp = 0;
            con = new SqlConnection("Data Source=" + sb1 + ";Initial Catalog=" + ufdata + ";User ID=" + sb2 + ";Password=" + sb3 + "");
            try
            {
                string sql = string.Format("select top 1 cDepCode  from Department where cDepCode like '99%' order by cdepcode desc");
                SqlCommand com = new SqlCommand(sql, con);
                con.Open();
                temp = Convert.ToInt32(com.ExecuteScalar());
                temp++;
                bmid = temp.ToString();
            }
            catch
            {

            }
            finally
            {
                con.Close();
            }
        }
        //
        private void selectDepartment_cDepCodeBY()
        {
            int temp = 0;
            con = new SqlConnection("Data Source=" + sb1 + ";Initial Catalog=" + ufdata + ";User ID=" + sb2 + ";Password=" + sb3 + "");
            try
            {
                string sql = string.Format("select top 1 cDepCode  from Department where cDepCode like '99%' order by cdepcode desc");
                SqlCommand com = new SqlCommand(sql, con);
                con.Open();
                temp = Convert.ToInt32(com.ExecuteScalar());
                temp++;
                bmid = temp.ToString();
            }
            catch
            {

            }
            finally
            {
                con.Close();
            }
        }

        private void selectPerson_cDepCode()
        {
            int temp = 0;
            con = new SqlConnection("Data Source=" + sb1 + ";Initial Catalog=" + ufdata + ";User ID=" + sb2 + ";Password=" + sb3 + "");
            try
            {
                string sql = string.Format("select cDepCode  from Person where cPersonCode = '{0}'",khbm);
                SqlCommand com = new SqlCommand(sql, con);
                con.Open();
                tempDepCode = com.ExecuteScalar().ToString();
                //temp++;
                //bmid = temp.ToString();
            }
            catch
            {

            }
            finally
            {
                con.Close();
            }
        }

        private void insertDepartment(int i)
        {
            string errString = string.Empty;
            con = new SqlConnection("Data Source=" + sb1 + ";Initial Catalog=" + ufdata + ";User ID=" + sb2 + ";Password=" + sb3 + "");
            int isok = 0;
            try
            {
                string sql = string.Format(@"Insert Into Department(cDepCode,bDepEnd,cDepName,iDepGrade) values('{0}','{1}','{2}','{3}')
                                            ", bmid, 1, bmmc, 2);
                SqlCommand com = new SqlCommand(sql, con);
                con.Open();
                isok = Convert.ToInt32(com.ExecuteNonQuery());
            }
            catch (SqlException e)
            {
                //txtInfo.Text += sql + "\n";
                errString = e.ToString();
            }
            finally
            {
                con.Close();
            }
            if (isok > 0)
            {
                txtInfo.Text += i + 8 + "新建部门成功！" + "\n";
            }
            else
            {
                txtInfo.Text += i + 8 + "新建部门失败！原因" + errString + "\n";
            }
        }

        private bool selectPerson()
        {
            int isok = 0;
            con = new SqlConnection("Data Source=" + sb1 + ";Initial Catalog=" + ufdata + ";User ID=" + sb2 + ";Password=" + sb3 + "");
            try
            {
                string sql = string.Format("select count(*) from Person where cPersonCode='{0}'", khbm);
                SqlCommand com = new SqlCommand(sql, con);
                con.Open();
                isok = Convert.ToInt32(com.ExecuteScalar());
            }
            catch
            {

            }
            finally
            {
                con.Close();
            }
            if (isok > 0)
            {
                return true;
            }
            return false;
        }

        private void insertPerson(int i)
        {
            string errString = string.Empty;
            con = new SqlConnection("Data Source=" + sb1 + ";Initial Catalog=" + ufdata + ";User ID=" + sb2 + ";Password=" + sb3 + "");
            int isok = 0;
            try
            {
                string sql = string.Format(@"Insert Into Person(cPersonCode,cPersonName,cDepCode) values('{0}','{1}','{2}')
                                            ", khbm, khjc,  99);
                SqlCommand com = new SqlCommand(sql, con);
                con.Open();
                isok = Convert.ToInt32(com.ExecuteNonQuery());
            }
            catch (SqlException e)
            {
                //txtInfo.Text += sql + "\n";
                errString = e.ToString();
            }
            finally
            {
                con.Close();
            }
            if (isok > 0)
            {
                txtInfo.Text += i + 8 + "新建个人成功！" + "\n";
            }
            else
            {
                txtInfo.Text += i + 8 + "新建个人失败！原因" + errString + "\n";
            }
        }

        private bool selectCustomer()
        {
            int isok = 0;
            con = new SqlConnection("Data Source=" + sb1 + ";Initial Catalog=" + ufdata + ";User ID=" + sb2 + ";Password=" + sb3 + "");
            try
            {
                string sql = string.Format("select count(*) from Customer where cCusCode='{0}'", khbm);
                SqlCommand com = new SqlCommand(sql, con);
                con.Open();
                isok = Convert.ToInt32(com.ExecuteScalar());
            }
            catch
            {

            }
            finally
            {
                con.Close();
            }
            if (isok > 0)
            {
                return true;
            }
            return false;
        }

        private void insertCustomer(int i)
        {
            string errString = string.Empty;
            con = new SqlConnection("Data Source=" + sb1 + ";Initial Catalog=" + ufdata + ";User ID=" + sb2 + ";Password=" + sb3 + "");
            int isok = 0;
            try
            {
                string sql = string.Format(@"Insert Into Customer(cCusCode,cCusName,cCusAbbName,cCCCode) values('{0}','{1}','{2}','{3}')
                                            ", khbm, khjc + "_TW", khjc + "_TW", 99);
                SqlCommand com = new SqlCommand(sql, con);
                con.Open();
                isok = Convert.ToInt32(com.ExecuteNonQuery());
            }
            catch (SqlException e)
            {
                //txtInfo.Text += sql + "\n";
                errString = e.ToString();
            }
            finally
            {
                con.Close();
            }
            if (isok > 0)
            {
                txtInfo.Text += i + 8 + "新建客户成功！" + "\n";
            }
            else
            {
                txtInfo.Text += i + 8 + "新建客户失败！原因" + errString + "\n";
            }
        }

        private bool selectVendor()
        {
            int isok = 0;
            con = new SqlConnection("Data Source=" + sb1 + ";Initial Catalog=" + ufdata + ";User ID=" + sb2 + ";Password=" + sb3 + "");
            try
            {
                string sql = string.Format("select count(*) from Vendor where cVenCode='{0}'", khbm);
                SqlCommand com = new SqlCommand(sql, con);
                con.Open();
                isok = Convert.ToInt32(com.ExecuteScalar());
            }
            catch
            {
            }
            finally
            {
                con.Close();
            }
            if (isok > 0)
            {
                return true;
            }
            return false;
        }

        private void insertVendor(int i)
        {
            string errString = string.Empty;
            con = new SqlConnection("Data Source=" + sb1 + ";Initial Catalog=" + ufdata + ";User ID=" + sb2 + ";Password=" + sb3 + "");
            int isok = 0;
            try
            {
                string sql = string.Format(@"Insert Into Vendor(cVenCode ,cVenName ,cVenAbbName ,cVCCode) values('{0}','{1}','{2}','{3}')
                                            ", khbm, khjc + "_TW", khjc + "_TW", 99);
                SqlCommand com = new SqlCommand(sql, con);
                con.Open();
                isok = Convert.ToInt32(com.ExecuteNonQuery());
            }
            catch (SqlException e)
            {
                //txtInfo.Text += sql + "\n";
                errString = e.ToString();
            }
            finally
            {
                con.Close();
            }
            if (isok > 0)
            {
                txtInfo.Text += i + 8 + "新建供应商成功！" + "\n";
            }
            else
            {
                txtInfo.Text += i + 8 + "新建供应商失败！原因" + errString + "\n";
            }
        }

        private bool selectFitemss97()
        {
            int isok = 0;
            con = new SqlConnection("Data Source=" + sb1 + ";Initial Catalog=" + ufdata + ";User ID=" + sb2 + ";Password=" + sb3 + "");
            try
            {
                string sql = string.Format("select count(*) from fitemss00 where citemcode='{0}'", gddm);
                SqlCommand com = new SqlCommand(sql, con);
                con.Open();
                isok = Convert.ToInt32(com.ExecuteScalar());
            }
            catch
            {

            }
            finally
            {
                con.Close();
            }
            if (isok > 0)
            {
                return true;
            }
            return false;
        }

        private void insertFitemss97(int i)
        {
            string errString = string.Empty;
            con = new SqlConnection("Data Source=" + sb1 + ";Initial Catalog=" + ufdata + ";User ID=" + sb2 + ";Password=" + sb3 + "");
            int isok = 0;
            try
            {
                string sql = string.Format(@"Insert Into fitemss00(citemcode,citemname,bclose,citemccode) values('{0}','{1}','{2}','{3}')
                                            ", gddm, gdjc, 0, 2);
                SqlCommand com = new SqlCommand(sql, con);
                con.Open();
                isok = Convert.ToInt32(com.ExecuteNonQuery());
            }
            catch (SqlException e)
            {
                //txtInfo.Text += sql + "\n";
                errString = e.ToString();
            }
            finally
            {
                con.Close();
            }
            if (isok > 0)
            {
                txtInfo.Text += i + 8 + "新建项目成功！" + "\n";
            }
            else
            {
                txtInfo.Text += i + 8 + "新建项目失败！原因" + errString + "\n";
            }
        }

        private void selectGL_accvouch()
        {
            con = new SqlConnection("Data Source=" + sb1 + ";Initial Catalog=" + ufdata + ";User ID=" + sb2 + ";Password=" + sb3 + "");
            try
            {
                string sql = string.Format("select max(ino_id) from GL_accvouch");
                SqlCommand com = new SqlCommand(sql, con);
                con.Open();
                ino_id = Convert.ToInt32(com.ExecuteScalar());
                
            }
            catch
            {

            }
            finally
            {
                con.Close();
            }
        }

        private void insertGL_accvouch(int type,int i)
        {
            string today = DateTime.Parse(DateTime.Now.ToString()).ToString("yyyy-MM-dd");
            con = new SqlConnection("Data Source=" + sb1 + ";Initial Catalog=" + ufdata + ";User ID=" + sb2 + ";Password=" + sb3 + "");
            int isok = 0;
            string sql = string.Empty;
            try
            {
                switch (type)
                { 
                    case 1:
                        sql = string.Format(@"insert into GL_accvouch(iperiod,csign,isignseq,ino_id,inid,dbill_date,idoc,cbill,cdigest,ccode,md,mc,doutbilldate,ioutperiod,bvouchedit,bvalueedit,bcodeedit,bPCSedit,bDeptedit,bItemedit,cDefine7,coutno_id,ctext1,ctext2,csup_id,cdept_id,cperson_id,ccus_id,citem_id,citem_class)values('{0}','记',1,'{1}','{2}','{3}','-1','demo','{4}','{5}','{6}','{7}','{8}',null,'true','true','true','true','true','true',null,'{9}','{10}','{11}',null,null,null,null,'{12}','00')", DateTime.Now.Month.ToString(), ino_id, inid, today, zy, kmbm, jfje, dfje, today, coutno_id, cText1, cText2, gddm);
                        break;
                    case 2:
                        sql = string.Format(@"insert into GL_accvouch(iperiod,csign,isignseq,ino_id,inid,dbill_date,idoc,cbill,cdigest,ccode,md,mc,doutbilldate,ioutperiod,bvouchedit,bvalueedit,bcodeedit,bPCSedit,bDeptedit,bItemedit,cDefine7,coutno_id,ctext1,ctext2,csup_id,cdept_id,cperson_id,ccus_id,citem_id,citem_class)values('{0}','记',1,'{1}','{2}','{3}','-1','demo','{4}','{5}','{6}','{7}','{8}',null,'true','true','true','true','true','true',null,'{9}','{10}','{11}','{12}',null,null,null,null,null)", DateTime.Now.Month.ToString(), ino_id, inid, today, zy, kmbm, jfje, dfje, today, coutno_id, cText1, cText2, khbm);
                        break;
                    case 3:
                        sql = string.Format(@"insert into GL_accvouch(iperiod,csign,isignseq,ino_id,inid,dbill_date,idoc,cbill,cdigest,ccode,md,mc,doutbilldate,ioutperiod,bvouchedit,bvalueedit,bcodeedit,bPCSedit,bDeptedit,bItemedit,cDefine7,coutno_id,ctext1,ctext2,csup_id,cdept_id,cperson_id,ccus_id,citem_id,citem_class)values('{0}','记',1,'{1}','{2}','{3}','-1','demo','{4}','{5}','{6}','{7}','{8}',null,'true','true','true','true','true','true',null,'{9}','{10}','{11}',null,'{12}',null,null,null,null)", DateTime.Now.Month.ToString(), ino_id, inid, today, zy, kmbm, jfje, dfje, today, coutno_id, cText1, cText2, bmid);
                        break;
                    case 4:
                        sql = string.Format(@"insert into GL_accvouch(iperiod,csign,isignseq,ino_id,inid,dbill_date,idoc,cbill,cdigest,ccode,md,mc,doutbilldate,ioutperiod,bvouchedit,bvalueedit,bcodeedit,bPCSedit,bDeptedit,bItemedit,cDefine7,coutno_id,ctext1,ctext2,csup_id,cdept_id,cperson_id,ccus_id,citem_id,citem_class)values('{0}','记',1,'{1}','{2}','{3}','-1','demo','{4}','{5}','{6}','{7}','{8}',null,'true','true','true','true','true','true',null,'{9}','{10}','{11}',null,null,null,'{12}',null,null)", DateTime.Now.Month.ToString(), ino_id, inid, today, zy, kmbm, jfje, dfje, today, coutno_id, cText1, cText2, khbm);
                        break;
                    case 5:
                        sql = string.Format(@"insert into GL_accvouch(iperiod,csign,isignseq,ino_id,inid,dbill_date,idoc,cbill,cdigest,ccode,md,mc,doutbilldate,ioutperiod,bvouchedit,bvalueedit,bcodeedit,bPCSedit,bDeptedit,bItemedit,cDefine7,coutno_id,ctext1,ctext2,csup_id,cdept_id,cperson_id,ccus_id,citem_id,citem_class)values('{0}','记',1,'{1}','{2}','{3}','-1','demo','{4}','{5}','{6}','{7}','{8}',null,'true','true','true','true','true','true',null,'{9}','{10}','{11}',null,'{12}',null,'{14}','{13}','00')", DateTime.Now.Month.ToString(), ino_id, inid, today, zy, kmbm, jfje, dfje, today, coutno_id, cText1, cText2, khbm, gddm, bmid);
                        break;
                    case 6:
                        sql = string.Format(@"insert into GL_accvouch(iperiod,csign,isignseq,ino_id,inid,dbill_date,idoc,cbill,cdigest,ccode,md,mc,doutbilldate,ioutperiod,bvouchedit,bvalueedit,bcodeedit,bPCSedit,bDeptedit,bItemedit,cDefine7,coutno_id,ctext1,ctext2,csup_id,cdept_id,cperson_id,ccus_id,citem_id,citem_class)values('{0}','记',1,'{1}','{2}','{3}','-1','demo','{4}','{5}','{6}','{7}','{8}',null,'true','true','true','true','true','true',null,'{9}','{10}','{11}','{12}',null,null,'{14}','{13}','00')", DateTime.Now.Month.ToString(), ino_id, inid, today, zy, kmbm, jfje, dfje, today, coutno_id, cText1, cText2, khbm, gddm, bmid);
                        break;
                    case 7:
                        sql = string.Format(@"insert into GL_accvouch(iperiod,csign,isignseq,ino_id,inid,dbill_date,idoc,cbill,cdigest,ccode,md,mc,doutbilldate,ioutperiod,bvouchedit,bvalueedit,bcodeedit,bPCSedit,bDeptedit,bItemedit,cDefine7,coutno_id,ctext1,ctext2,csup_id,cdept_id,cperson_id,ccus_id,citem_id,citem_class)values('{0}','记',1,'{1}','{2}','{3}','-1','demo','{4}','{5}','{6}','{7}','{8}',null,'true','true','true','true','true','true',null,'{9}','{10}','{11}',null,null,'{12}',null,'{13}','00')", DateTime.Now.Month.ToString(), ino_id, inid, today, zy, kmbm, jfje, dfje, today, coutno_id, cText1, cText2, khbm, gddm);
                        break;
                    case 8:
                        sql = string.Format(@"insert into GL_accvouch(iperiod,csign,isignseq,ino_id,inid,dbill_date,idoc,cbill,cdigest,ccode,md,mc,doutbilldate,ioutperiod,bvouchedit,bvalueedit,bcodeedit,bPCSedit,bDeptedit,bItemedit,cDefine7,coutno_id,ctext1,ctext2,csup_id,cdept_id,cperson_id,ccus_id,citem_id,citem_class)values('{0}','记',1,'{1}','{2}','{3}','-1','demo','{4}','{5}','{6}','{7}','{8}',null,'true','true','true','true','true','true',null,'{9}','{10}','{11}','{12}',null,null,null,'{13}','00')", DateTime.Now.Month.ToString(), ino_id, inid, today, zy, kmbm, jfje, dfje, today, coutno_id, cText1, cText2, khbm,gddm);
                        break;
                    case 9:
                        sql = string.Format(@"insert into GL_accvouch(iperiod,csign,isignseq,ino_id,inid,dbill_date,idoc,cbill,cdigest,ccode,md,mc,doutbilldate,ioutperiod,bvouchedit,bvalueedit,bcodeedit,bPCSedit,bDeptedit,bItemedit,cDefine7,coutno_id,ctext1,ctext2,csup_id,cdept_id,cperson_id,ccus_id,citem_id,citem_class)values('{0}','记',1,'{1}','{2}','{3}','-1','demo','{4}','{5}','{6}','{7}','{8}',null,'true','true','true','true','true','true',null,'{9}','{10}','{11}',null,null,null,'{12}','{13}','00')", DateTime.Now.Month.ToString(), ino_id, inid, today, zy, kmbm, jfje, dfje, today, coutno_id, cText1, cText2, khbm, gddm);
                        break;
                    case 10:
                        sql = string.Format(@"insert into GL_accvouch(iperiod,csign,isignseq,ino_id,inid,dbill_date,idoc,cbill,cdigest,ccode,md,mc,doutbilldate,ioutperiod,bvouchedit,bvalueedit,bcodeedit,bPCSedit,bDeptedit,bItemedit,cDefine7,coutno_id,ctext1,ctext2,csup_id,cdept_id,cperson_id,ccus_id,citem_id,citem_class)values('{0}','记',1,'{1}','{2}','{3}','-1','demo','{4}','{5}','{6}','{7}','{8}',null,'true','true','true','true','true','true',null,'{9}','{10}','{11}',null,'{12}',null,null,'{13}','00')", DateTime.Now.Month.ToString(), ino_id, inid, today, zy, kmbm, jfje, dfje, today, coutno_id, cText1, cText2, khbm, gddm);
                        break;
                    case 11:
                        sql = string.Format(@"insert into GL_accvouch(iperiod,csign,isignseq,ino_id,inid,dbill_date,idoc,cbill,cdigest,ccode,md,mc,doutbilldate,ioutperiod,bvouchedit,bvalueedit,bcodeedit,bPCSedit,bDeptedit,bItemedit,cDefine7,coutno_id,ctext1,ctext2,csup_id,cdept_id,cperson_id,ccus_id,citem_id,citem_class)values('{0}','记',1,'{1}','{2}','{3}','-1','demo','{4}','{5}','{6}','{7}','{8}',null,'true','true','true','true','true','true',null,'{9}','{10}','{11}',null,null,null,null,null,null)", DateTime.Now.Month.ToString(), ino_id, inid, today, zy, kmbm, jfje, dfje, today, coutno_id, cText1, cText2);
                        break;
                    case 12:
                        sql = string.Format(@"insert into GL_accvouch(iperiod,csign,isignseq,ino_id,inid,dbill_date,idoc,cbill,cdigest,ccode,md,mc,doutbilldate,ioutperiod,bvouchedit,bvalueedit,bcodeedit,bPCSedit,bDeptedit,bItemedit,cDefine7,coutno_id,ctext1,ctext2,csup_id,cdept_id,cperson_id,ccus_id,citem_id,citem_class)values('{0}','记',1,'{1}','{2}','{3}','-1','demo','{4}','{5}','{6}','{7}','{8}',null,'true','true','true','true','true','true',null,'{9}','{10}','{11}',null,'{13}','{12}',null,null,null)", DateTime.Now.Month.ToString(), ino_id, inid, today, zy, kmbm, jfje, dfje, today, coutno_id, cText1, cText2, khbm,tempDepCode);
                        break;
                }
                SqlCommand com = new SqlCommand(sql, con);
                con.Open();
                isok = Convert.ToInt32(com.ExecuteNonQuery());
            }
            catch (SqlException e)
            {

            }
            finally
            {
                con.Close();
            }
            if (isok > 0)
            {
                txtInfo.Text += i + 8 + "导入凭证成功！" + "\n";
            }
            else
            {
                txtInfo.Text += i + 8 + "导入凭证失败！" + "\n";
            }
        }

        private void updateAp_CancelNo()
        {
            selectGL_accvouch();
            con = new SqlConnection("Data Source=" + sb1 + ";Initial Catalog=" + ufdata + ";User ID=" + sb2 + ";Password=" + sb3 + "");
            try
            {
                string sql = string.Format("update Ap_CancelNo set iCancelNo = '" + ino_id + "' where cType = 'PZ' and cFlag = 'GL'");
                SqlCommand com = new SqlCommand(sql, con);
                con.Open();
                com.ExecuteNonQuery();
            }
            catch
            {

            }
            finally
            {
                con.Close();
            }
        }
        #endregion

        /// <summary>
        /// 日志
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnLog_Click(object sender, EventArgs e)
        {
            if (txtInfo.Text == "")
            {
                MessageBox.Show("没有日志！");
                return;
            }
            string s = "\n";
            string s1 = "\r\n";
            string str = this.txtInfo.Text;
            str = str.Replace(s, s1);
            string tempURL = string.Empty;
            string finalURL = string.Empty;
            if (logType == 1)
            {
                if (billType == 1)
                {
                    tempURL = Application.StartupPath + "\\CheckLog\\" + "\\采购入库单\\";
                    Directory.CreateDirectory(tempURL);
                    finalURL = tempURL + "\\" + logTime + ".txt";
                }
                if (billType == 2)
                {
                    tempURL = Application.StartupPath + "\\CheckLog\\" + "\\销售出库单\\";
                    Directory.CreateDirectory(tempURL);
                    finalURL = tempURL + "\\" + logTime + ".txt";
                }
                if (billType == 3)
                {
                    tempURL = Application.StartupPath + "\\CheckLog\\" + "\\其他出库单\\";
                    Directory.CreateDirectory(tempURL);
                    finalURL = tempURL + "\\" + logTime + ".txt";
                }
            }
            else
            {
                if (billType == 1)
                {
                    tempURL = Application.StartupPath + "\\Log\\" + "\\采购入库单\\";
                    Directory.CreateDirectory(tempURL);
                    finalURL = tempURL + "\\" + logTime + ".txt";
                }
                if (billType == 2)
                {
                    tempURL = Application.StartupPath + "\\Log\\" + "\\销售出库单\\";
                    Directory.CreateDirectory(tempURL);
                    finalURL = tempURL + "\\" + logTime + ".txt";
                }
                if (billType == 3)
                {
                    tempURL = Application.StartupPath + "\\Log\\" + "\\其他出库单\\";
                    Directory.CreateDirectory(tempURL);
                    finalURL = tempURL + "\\" + logTime + ".txt";
                }
            }
            try
            {
                File.WriteAllText(finalURL, str);//保存日志
                txtInfo.Text = "";
            }
            catch
            {
                MessageBox.Show("日志文件生成失败！");
            }
        }


    }
}